package com.besttone.search;

import java.io.File;
import java.io.IOException;
import java.util.List;

import com.besttone.http.UpdateRequest;
import com.besttone.http.UpdateRequest.UpdateListener;
import com.besttone.search.Client.GetLocationAdressListener;
import com.besttone.search.dialog.ProgressBarDialog;
import com.besttone.search.model.City;
import com.besttone.search.model.PhoneInfo;
import com.besttone.search.sql.NativeDBHelper;
import com.besttone.search.util.CellInfoManager;
import com.besttone.search.util.CellLocationManager;
import com.besttone.search.util.Constants;
import com.besttone.search.util.LogUtils;
import com.besttone.search.util.PhoneUtil;
import com.besttone.search.util.SharedUtils;
import com.besttone.search.util.StringUtils;
import com.besttone.search.util.WifiInfoManager;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
//import android.location.Address;
//import android.location.Geocoder;
import android.location.Address;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.amap.cn.apis.util.ConstantsAmap;
import com.amap.mapapi.core.AMapException;
import com.amap.mapapi.core.GeoPoint;
import com.amap.mapapi.geocoder.Geocoder;
import com.amap.mapapi.map.MapActivity;
import com.amap.mapapi.map.MapView;

public class SplashActivity extends Activity {
	private final int TIME_UP = 1;
	protected Context mContext;
	protected UpdateRequest r;	

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == TIME_UP) {
				Intent intent = new Intent();
				intent.setClass(SplashActivity.this, MainActivity.class);
				startActivity(intent);
				overridePendingTransition(R.anim.splash_screen_fade,
						R.anim.splash_screen_hold);
				SplashActivity.this.finish();
			}
		}
	};

	public void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(R.layout.splash_screen_view);
		initApp();
		initPhoneInfo();		
		Client.initWithContext(this);
		initCity();
//		progDialog=new ProgressDialog(this);
//
//		detectUpdate();
		new Thread() {
			public void run() {
				try {
					Thread.sleep(500);
				} catch (Exception e) {

				}
				Message msg = new Message();
				msg.what = TIME_UP;
				handler.sendMessage(msg);
			}
		}.start();

	}

	private void initApp() {
		initNativeDB();
	}

	private void initNativeDB() {
		SharedPreferences localSharedPreferences = getSharedPreferences(
				"NativeDB", 0);
		if (1 > localSharedPreferences.getInt("Version", 0)) {
			Constants.copyNativeDB(this,
					getResources().openRawResource(R.raw.native_database));
			localSharedPreferences.edit().putInt("Version", 1).commit();
		}
		Constants.copyNativeDB(this,
				getResources().openRawResource(R.raw.native_database));
		localSharedPreferences.edit().putInt("Version", 1).commit();
	}
	
	private boolean isUnSelectedCity() {
		if ((!SharedUtils.isFirstSelectedCityComplete(this.mContext))
				|| (StringUtils.isEmpty(SharedUtils
						.getCurrentCityName(this.mContext)))
				|| (StringUtils.isEmpty(SharedUtils
						.getCurrentCityCode(this.mContext)))
				|| (StringUtils.isEmpty(SharedUtils
						.getCurrentProvinceCode(this.mContext)))) {
			return true;
		}
		return false;
	}
	
	private void initCity() {
//		SharedUtils.setCurrentCity(Client.getContext(), SharedUtils.selectCity());
		City localCity = new City();
		localCity.setCityName("上海");
		localCity.setCityCode("310000");
		localCity.setSimplifyCode("31");
		localCity.setCityId("75");
		localCity.setProvinceCode("310000");

		if(SharedUtils.getLastLocationCity()!=null)
			localCity=SharedUtils.getLastLocationCity();
		SharedUtils.setCurrentCity(this, localCity);
	}
	
	public void initPhoneInfo() {
		TelephonyManager tm = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
		String imei = tm.getDeviceId(); //IMEI
		String provider = tm.getNetworkOperatorName(); //运营商
		String imsi = tm.getSubscriberId(); //IMSI
		PhoneUtil util = new PhoneUtil();
		PhoneInfo info = null;
		try {
			if(NetWorkStatus()) {
				//info = util.getPhoneNoByIMSI(imsi);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(info==null)
			info = new PhoneInfo();
		info.setImei(imei);
		info.setImsi(imsi);
		info.setProvider(provider);
		SharedUtils.setCurrentPhoneInfo(this, info);
	}
	
    private boolean NetWorkStatus() {
    	boolean netSataus = false;
    	ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    	cwjManager.getActiveNetworkInfo();
    	if (cwjManager.getActiveNetworkInfo() != null) {
    		netSataus = cwjManager.getActiveNetworkInfo().isAvailable();
    	}
//    	if (netSataus) {
//    		Builder b = new AlertDialog.Builder(this).setTitle("没有可用的网络").setMessage("是否对网络进行设置?");
//    		b.setPositiveButton("是", new DialogInterface.OnClickListener() {
//    			public void onClick(DialogInterface dialog, int whichButton) {
//    				Intent mIntent = new Intent("/");
//    				ComponentName comp = new ComponentName("com.android.settings", 
//    						"com.android.settings.WirelessSettings");
//    				mIntent.setComponent(comp);
//    				mIntent.setAction("android.intent.action.VIEW");
//    				startActivityForResult(mIntent,0); // 如果在设置完成后需要再次进行操作，可以重写操作代码，在这里不再重写
//    			}
//    		}).setNeutralButton("否", new DialogInterface.OnClickListener() {
//    			public void onClick(DialogInterface dialog, int whichButton) {
//    				dialog.cancel();
//    			}
//    		}).show();	
//    	}
    	return netSataus;
    }
    
    private void detectUpdate() {
    	r = new UpdateRequest();
		r.setListener(new UpdateListener() {
			@Override
			public void onUpdateNoNeed(String msg) {
				gotoLogin();
			}
			
			public void onUpdateMust(final String msg, final String url) {
				Client.postRunnable(new Runnable()
				{
					
					@Override
					public void run()
					{
						// TODO Auto-generated method stub
						AlertDialog.Builder b = new AlertDialog.Builder(SplashActivity.this);
						b.setTitle("程序必须升级才能继续");
						b.setMessage(msg+"\r\n"+url);
						b.setNegativeButton("取消", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								finish();
								System.gc();
							}
						});
						b.setPositiveButton("升级",new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								gotoUpdate(url);
							}
						});
						b.setCancelable(false);
						b.show();
					}
				});				
				
				
			}
			
			public void onUpdateError(short code, Exception e) {
				Client.postRunnable(new Runnable()
				{
					
					@Override
					public void run()
					{
						// TODO Auto-generated method stub
						AlertDialog.Builder b = new AlertDialog.Builder(SplashActivity.this);
						b.setTitle("升级验证失败");
						b.setMessage("请检查网络...");
						b.setNegativeButton("取消", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								finish();
								System.gc();
							}
						});
						b.setCancelable(false);
						b.show();
					}
				});
				
			}
			
			public void onUpdateAvaiable(final String msg, final String url) {
				Client.postRunnable(new Runnable()
				{
					
					@Override
					public void run()
					{
						// TODO Auto-generated method stub
						AlertDialog.Builder b = new AlertDialog.Builder(SplashActivity.this);
						b.setTitle(R.string.update_title);
						b.setMessage(msg+"\r\n"+url);
						b.setNegativeButton("取消", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								gotoLogin();
							}
						});
						b.setPositiveButton("升级",new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								gotoUpdate(url);
							}
						});
						b.setCancelable(false);
						b.show();
					}
				});
				
			}
		});
		
		if (Client.decetNetworkOn())
		{
//			Log.d("check","on");
			r.checkUpdate();
		}
		else {
//			Log.d("check","off");
			gotoLogin();
			Toast.makeText(SplashActivity.this, "网络异常，没有可用网络",
					Toast.LENGTH_SHORT).show();
		}
		
	}
	
	private void gotoLogin() {	
		getLoacation();			
	}
	
    private void gotoUpdate(String url) {

		if (TextUtils.isEmpty(url)) {
    		Toast.makeText(this, "升级的地址有误", Toast.LENGTH_SHORT).show();
    		finish();
    		System.gc();
    		return;
    	}
//		url = url.toLowerCase();
		if (url.startsWith("www")) {
			url = "http://" + url;
		}
		if (url.startsWith("http")) {
	    	try {
//	    		Uri u = Uri.parse(url);
	    		ProgressBarDialog pbd=new ProgressBarDialog(SplashActivity.this);
	    		pbd.setTitle("下载中");
	    		pbd.setOnCancelListener(new OnCancelListener() {
					
					@Override
					public void onCancel(DialogInterface dialog) {
						// TODO Auto-generated method stub
						gotoLogin();
					}
				});
	    		pbd.show();
	    		pbd.downLoadFile(url);
//	    		Intent i = new Intent( Intent.ACTION_VIEW, u );
//	    		startActivity( i );
//	    		finish();
	    		System.gc();
	    	} catch(Exception e) {
	    		e.printStackTrace();
	    	}
		}
	}
    
    private ProgressDialog progDialog = null;
	private Geocoder coder;
	private String addressName;
	private double mLat = 31.130704;
	private double mLon = 121.5334131;
    public void getLoacation(){
    	Client.getInstance().setmLoactionDlistener(new GetLocationAdressListener()
		{
			
			@Override
			public void onGetLocationAdress()
			{
				// TODO Auto-generated method stub
				Client.getInstance().disableMyLocation();
				initCity();
				new Thread() {
					public void run() {
						try {
							Thread.sleep(500);
						} catch (Exception e) {

						}
						Message msg = new Message();
						msg.what = TIME_UP;
						handler.sendMessage(msg);
					}
				}.start();
			}

			@Override
			public void onFialedGetLocationAdress()
			{
				// TODO Auto-generated method stub
				Client.postRunnable(new Runnable()
				{
					
					@Override
					public void run()
					{
						// TODO Auto-generated method stub

						showExitAlert();
					}
				});
			}
		});
    	Client.getInstance().enableMyLocation();
//    	Client.getInstance().tryGetAddress(30.783298, 120.376826);
//    	CellInfoManager cellManager = new CellInfoManager(this)
//
//        WifiInfoManager wifiManager = new WifiInfoManager(this);
//        
//        Log.d("location","init");
//        
//        coder = new Geocoder(Client.getContext());
//
//        CellLocationManager locationManager = new CellLocationManager(this, cellManager, wifiManager) {
//
//               @Override
//
//               public void onLocationChanged() {
//
//                      Log.d("location",this.latitude() + "-" + this.longitude());
//                      
//                      Client.getInstance().getAddress(this.latitude(),this.longitude());
//                      
//                      this.stop();
//
//               }
//
//        };
//
//        locationManager.start();
    }
    
	private void showExitAlert() {
        new AlertDialog.Builder(this)
        .setTitle(R.string.prompt)
        .setMessage(R.string.quit_without_connection)
        .setCancelable(false)
        .setPositiveButton(R.string.confirm,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int whichButton) {
                    	exitApp();
                    }
                }).show();
	}
	
	//彻底关闭程序
	protected void exitApp() {
	    super.onDestroy();
	    Client.release();
	    System.exit(0);
	    // 或者下面这种方式
	    // android.os.Process.killProcess(android.os.Process.myPid());
	} 
   
}
